/*
 * Copyright 2008-2010 Daniel Cachapa <cachapa@gmail.com>
 * 
 * This program is distributed under the terms of the GNU General Public License Version 3
 * The license can be read in its entirety in the LICENSE.txt file accompanying this source code,
 * or at: http://www.gnu.org/copyleft/gpl.html
 * 
 * This file is part of Libra.
 *
 * WeightWatch is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * WeightWatch is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the WeightWatch source code. If not, see: http://www.gnu.org/licenses
 */

package net.cachapa.libra;

import java.util.ArrayList;

import net.cachapa.libra.component.ValueSelector;
import net.cachapa.libra.data.Database;
import net.cachapa.libra.data.Value;
import net.cachapa.libra.util.MyDate;
import net.cachapa.libra.util.UnitManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;
import android.widget.DatePicker.OnDateChangedListener;

public class InsertValue extends Activity implements OnClickListener, OnDateChangedListener {
	public static final int DIALOG_UPDATE_VALUE = 0;
	private boolean editMode = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.insertvalue);
		
		DatePicker datePicker = (DatePicker) findViewById(R.id.DatePicker);
		Button okButton = (Button) findViewById(R.id.OkButton);
		Button cancelButton = (Button) findViewById(R.id.CancelButton);

		Intent editIntent = getIntent();
		int year = datePicker.getYear();
		int month = datePicker.getMonth() + 1;
		int day = datePicker.getDayOfMonth();
		float weight = -1;
		if (editIntent.hasExtra("weight")) {
			editMode = true;
			datePicker.setEnabled(false);
			okButton.setText(R.string.update);
			
			year = editIntent.getIntExtra("year", -1);
			month = editIntent.getIntExtra("month", -1);
			day = editIntent.getIntExtra("day", -1);
			weight = editIntent.getFloatExtra("weight", -1);
		}
		
		datePicker.init(year, month - 1, day, this);
		MyDate date = new MyDate(year, month, day);
		setTitle(String.format(getString(R.string.insert_value_title), date.toString()));
		
		UnitManager um = UnitManager.getInstance(this);
		if (weight == -1) {
			weight = um.getDefaultWeight();
			Database database = Database.getInstance(this);
			Value latestValue = database.getLatestValue();
			if (latestValue != null) {
				weight = latestValue.getWeight();
			}
		}
		
		ValueSelector weightValueSelector = (ValueSelector) findViewById(R.id.WeightValueSelector);
		weightValueSelector.initialize(um.getMinWeight(), um.getMaxWeight(), 1, ValueSelector.TYPE_WEIGHT);
		weightValueSelector.setValue(weight);
		weightValueSelector.setActivityCallback(this);
		
		okButton.setOnClickListener(this);
		cancelButton.setOnClickListener(this);
	}

	public void onClick(View v) {
		if (v == findViewById(R.id.OkButton)) {
			if (editMode) {
				updateValue();
			}
			else {
				insertValue();
			}
		}
		else if (v == findViewById(R.id.CancelButton)) {
			finish();
		}
	}

	private void insertValue() {
		DatePicker datePicker = (DatePicker) findViewById(R.id.DatePicker);
		MyDate date = new MyDate(datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth());
		ValueSelector weightValueSelector = (ValueSelector) findViewById(R.id.WeightValueSelector);
		float weight = weightValueSelector.getValue();
		
		Value value = new Value(date, weight);
		
		Database database = Database.getInstance(this);
		boolean result = database.insertValue(value);
		if (result) {
			Toast.makeText(this, R.string.value_inserted, Toast.LENGTH_SHORT).show();
			finish();
		}
		else {
			showDialog(DIALOG_UPDATE_VALUE);
		}
	}
	
	private void updateValue() {
		DatePicker datePicker = (DatePicker) findViewById(R.id.DatePicker);
		MyDate date = new MyDate(datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth());
		ValueSelector weightValueSelector = (ValueSelector) findViewById(R.id.WeightValueSelector);
		float weight = weightValueSelector.getValue();
		
		Value value = new Value(date, weight);
		
		Database database = Database.getInstance(this);
		boolean result = database.updateValue(value);
		if (result) {
			Toast.makeText(this, R.string.value_updated, Toast.LENGTH_SHORT).show();
			finish();
		}
		else {
			Toast.makeText(this, "Error updating", Toast.LENGTH_LONG).show();
		}
	}
	
	public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
		MyDate date = new MyDate(year, monthOfYear + 1, dayOfMonth);
		setTitle(String.format(getString(R.string.insert_value_title), date.toString()));
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_UPDATE_VALUE:
			DatePicker datePicker = (DatePicker) findViewById(R.id.DatePicker);
			MyDate date = new MyDate(datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth());
			
			float oldWeight = Database.getInstance(this).getValueByDate(date).getWeight();
			
			ValueSelector weightValueSelector = (ValueSelector) findViewById(R.id.WeightValueSelector);
			float newWeight = weightValueSelector.getValue();
			
			UnitManager um = UnitManager.getInstance(this);
			String message = String.format(getString(R.string.update_value_dialog),
					um.toWeightUnit(oldWeight), um.toWeightUnit(newWeight));
			
			return new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setTitle(R.string.update)
			.setMessage(message)
			.setPositiveButton(R.string.update, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					updateValue();
				}
			})
			.setNegativeButton(android.R.string.cancel, null)
			.create();
		}
		
		return null;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ValueSelector.VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
			ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			
			float value = -1;
			for (String match : matches) {
				try {
					value = Float.parseFloat(match);
					break;
				} catch (NumberFormatException e) {
					// Ignore
				}
			}
			
			if (value > 0) {
				ValueSelector weightValueSelector = (ValueSelector) findViewById(R.id.WeightValueSelector);
				weightValueSelector.setValue(value);
			}
			else {
				Toast.makeText(this, R.string.speak_value_failed, Toast.LENGTH_LONG).show();
			}
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
}
